package com.itanqing.qcim.service.impl;

import com.itanqing.qcim.dto.CodeLoginReqDto;
import com.itanqing.qcim.dto.LoginReqDto;
import com.itanqing.qcim.dto.RegisterReqDto;
import com.itanqing.qcim.dto.UserInfoResDto;
import com.itanqing.qcim.entity.TAccount;
import com.itanqing.qcim.entity.TUser;
import com.itanqing.qcim.mapper.TAccountMapper;
import com.itanqing.qcim.service.ITAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itanqing.qcim.service.ITUserService;
import com.xiaohuoren.dubbo.common.exception.AppException;
import com.xiaohuoren.dubbo.common.utils.PasswordUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zs
 * @since 2023-12-14
 */
@Service
public class TAccountServiceImpl extends ServiceImpl<TAccountMapper, TAccount> implements ITAccountService {

    @Resource
    private ITUserService iUserService;

    @Override
    @Transactional
    public void register(RegisterReqDto registerReqDto) {

        TUser user = iUserService.getByPhone(registerReqDto.getAccountName());

        if (user == null) {
            Long userId = iUserService.add(registerReqDto.getAccountName(), registerReqDto.getUserName());

            TAccount tAccount = new TAccount();
            tAccount.setUserId(userId);
            tAccount.setAccountName(registerReqDto.getAccountName());
            tAccount.setAccountType(1);
            tAccount.setUserId(userId);
            String plat = UUID.randomUUID().toString().replaceAll("-", "");
            tAccount.setSalt(plat);
            tAccount.setPassword(PasswordUtils.encode("123456", tAccount.getSalt()));

            this.baseMapper.insert(tAccount);

        } else {
            throw new AppException("账号以存在");
        }
    }

    @Override
    public UserInfoResDto login(LoginReqDto loginReqDto) {

        TAccount account = this.baseMapper.getAccount(loginReqDto.getAccountName());
        if (account == null) {
            throw new AppException("账户不存在");
        }
        UserInfoResDto userInfoResDto = new UserInfoResDto();
        userInfoResDto.setAccountName(account.getAccountName());
        userInfoResDto.setUserId(account.getUserId().toString());
        return userInfoResDto;
    }

    @Override
    public UserInfoResDto loginByCode(CodeLoginReqDto codeLoginReqDto) {
        return null;
    }

    @Override
    public TAccount checkPassword(String accountName, Integer accountType, String password) {
        return null;
    }
}
